#coding=utf-8
#author:dn_李四海(qq:653378495)
#动脑学院VIP
'''
1.计算range(1,99999)的总和,采取三种方式,第一:重复10次计算总时间;
 第二:开启十个子线程去计算;第三:开启十个进程去计算,然后对比耗时
'''
# import time
# start = time.clock()
# for r in range(10):
#    r+=1
#    s = 0
#    for i in range(1,99999):
#       s+=i
# print(s)
# end = time.clock()
# print('Running time: %s Seconds'%(end-start))
#############################################
# from threading import Thread,current_thread
# import time
# start = time.clock()
# def mk_thr(num):
#    thread_list = [Thread(target=mk_thr, args=(num,)) for num in range(1, 10)]
#    for thr in thread_list:
#       s = 0
#       for i in range(1,99999):
#          s+=i
#       print(s)
# end = time.clock()
# print('Running time: %s Seconds'%(end-start))
##############################################
# from multiprocessing import Process,Pool
# import time
# start = time.clock()
# if __name__=='__main__':
#    pool = Pool(10)
#    s = 0
#    for i in range(1,99999):
#       s+=i
#    print(s)
#    pool.close()
# end = time.clock()
# print('Running time: %s Seconds'%(end-start))
'''
2.将第一题计算十次改为使用线程池去计算,线程池线程个数由你自己电脑cpu逻辑核数决定
'''
from threading import Thread,Lock,current_thread
import time
start = time.clock()
money = 0
lock = Lock()
def run_money(num):
    global money
    try:
        lock.acquire()
        for i in range(num):     # 先存100,马上取100,先存后取,重复执行多少次,理想的结果依然为0
            money = money + num
    finally:
        lock.release()  # 释放锁对象
thr1 = Thread(target=run_money,args=(99999,))
thr2 = Thread(target=run_money,args=(99999,))
thr3 = Thread(target=run_money,args=(99999,))
thr4 = Thread(target=run_money,args=(99999,))

thr1.start()
thr2.start()
thr3.start()
thr4.start()
thr1.join()
thr2.join()
thr3.join()
thr4.join()
print('最后的money数目为',money)
end = time.clock()
print('Running time: %s Seconds'%(end-start))




